package cn.yhbk.web.modules.manager.Controller;

import cn.hutool.core.bean.BeanUtil;
import cn.yhbk.web.common.Util.MyUtil;
import cn.yhbk.web.common.api.CommonPage;
import cn.yhbk.web.common.api.CommonResult;
import cn.yhbk.web.common.exception.ApiException;
import cn.yhbk.web.common.service.OCRCService;
import cn.yhbk.web.modules.manager.Pojo.DTO.GpaCheck.CheckOperate;
import cn.yhbk.web.modules.manager.Pojo.DTO.GpaCheck.GpaCheckConditionDTO;
import cn.yhbk.web.modules.manager.Pojo.DTO.GpaCheck.Words;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbCounsellor;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbGpaFlowPath;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbGpaRecord;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbStudent;
import cn.yhbk.web.modules.manager.Pojo.VO.GpaCheck.*;
import cn.yhbk.web.modules.manager.Service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 有何不可
 * @since 2023-08-05
 */
@RestController
@Api(tags = "绩点评定")
@RequestMapping("/tbGpaCheck")
@Slf4j
public class TbGpaCheckController {

    @Autowired
    ITbGpaCheckService checkService;

    @Autowired
    ITbStudentService studentService;

    @Autowired
    ITbCounsellorService counsellorService;

    @Autowired
    ITbGpaFlowPathService flowPathService;

    @Autowired
    ITbGpaRecordService recordService;

    @Autowired
    OCRCService ocrcService;

    @ApiOperation("学生发起绩点申请")
    @PostMapping("/student")
    public CommonResult addCheck(@RequestBody GpaCheckAdd add) {

        Long adminId = MyUtil.getCurrentAdminId();
        Long studentId = studentService.getStudentIdByAdminId(adminId);

        TbGpaRecord record = recordService.getRecordByStudentId(studentId);


//        List<Words> wordsList = ocrcService.performOCR(imgUrls);
//        GpaCheckAdd add = checkService.getGpgByImg(wordsList);

        if (!record.getPass()) return CommonResult.failed("挂科不能申请!");
        System.out.println("test");
        boolean success = checkService.addCheck(add);
        if (success) return CommonResult.success("添加成功!");
        return CommonResult.failed("添加失败!");
    }

    @ApiOperation("学生查看自己得绩点申请")
    @GetMapping("/student")
    public CommonResult getCheckStudent(@RequestParam(name = "currentPage", defaultValue = "1") Long currentPage,
                                        @RequestParam(name = "pageSize", defaultValue = "5") Long pageSize,
                                        GpaCheckGetStu condition) {

        //设置学生id
        Long adminId = MyUtil.getCurrentAdminId();
        Long studentId = studentService.getStudentIdByAdminId(adminId);
        List<Long> studentIds = new ArrayList<>();
        studentIds.add(studentId);

        //构造查询条件
        GpaCheckConditionDTO conditionDTO = new GpaCheckConditionDTO();
        BeanUtil.copyProperties(condition, conditionDTO);
        conditionDTO.setStuIds(studentIds);

        CommonPage<GpaCheckResP> checks = checkService.getCheck(currentPage, pageSize, conditionDTO);


        return CommonResult.success(checks);
    }


    //辅导员查询
    //只能查询自己管理得班级得学生
    @ApiOperation("辅导员获取申请记录")
    @GetMapping("/counsellor")
    public CommonResult getCheckCounsellor(@RequestParam(name = "currentPage", defaultValue = "1") Long currentPage,
                                           @RequestParam(name = "pageSize", defaultValue = "5") Long pageSize,
                                           GpaCheckGetCon condition) {
        GpaCheckConditionDTO conditionDTO = new GpaCheckConditionDTO();
        BeanUtil.copyProperties(condition, conditionDTO);

        //添加学生
        List<Long> stuIds = new ArrayList<>();

        Long stuId = condition.getStuId();
        //拿到当前辅导员信息
        Long adminId = MyUtil.getCurrentAdminId();
        TbCounsellor counsellor = counsellorService.getCounsellorByAdminId(adminId);
        if (Objects.isNull(counsellor) || Objects.isNull(counsellor.getId())) {
            log.error("根据adminId获取辅导员信息为空或辅导员id为空");
            throw new ApiException("请求错误，请联系管理员");
        }

        if (Objects.isNull(stuId)) {
            List<Long> tmpStuIds = studentService.getStudentIdByCounsellorId(counsellor.getId());

            stuIds.addAll(tmpStuIds);
            log.debug("学生id：{}", stuIds);
        } else {

            //判断该学生是不是当前辅导员角色
            boolean exits = studentService.checkStudentByCounsellor(counsellor.getId(), stuId);
            if (!exits) return CommonResult.failed("该学生不是该辅导员班上的学生!");
            stuIds.add(stuId);
        }
        conditionDTO.setStuIds(stuIds);

//        //判断状态
//        Boolean status = condition.getStatus();
//        //为空，则表示查询全部,不做操作
//
//        //不为空
//        if (!Objects.isNull(status)) {
//            List<Integer> orderList = new ArrayList<>();
//            Integer order = flowPathService.getCurrentFlow();
//            if (status) {
//                //为true，则表示查询已经处理过的记录
//                Integer lastOrder = flowPathService.getLastOrder();
//
//                for (int i = order + 1; i <= lastOrder + 1; i++) {
//                    orderList.add(i);
//                }
//
//                //已经拒绝的申请记录
//                orderList.add(0);
//                log.debug("orderList:{}", orderList);
//            } else {
//                //为false，则表示查询还未处理,当前角色的顺序之前所有的
//                orderList.add(order);
//            }
//            conditionDTO.setStatus(orderList);
//        }
        Integer status = condition.getStatus();
        List<Integer> list = new ArrayList<>();
        if (!Objects.isNull(status)) {
            list.add(status);
        }
        conditionDTO.setStatus(list);

        CommonPage<GpaCheckResP> check = checkService.getCheck(currentPage, pageSize, conditionDTO);

        return CommonResult.success(check);
    }


    //材料审核员查询
    //只能查询自己学院得学生
    @ApiOperation("审核员查询申请记录")
    @GetMapping("/decide")
    public CommonResult getCheck(@RequestParam(name = "currentPage", defaultValue = "1") Long currentPage,
                                 @RequestParam(name = "pageSize", defaultValue = "5") Long pageSize,
                                 GpaCheckGetCon condition) {
        GpaCheckConditionDTO conditionDTO = new GpaCheckConditionDTO();
        BeanUtil.copyProperties(condition, conditionDTO);

        //添加学生
        List<Long> stuIds = new ArrayList<>();

        Long stuId = condition.getStuId();
        //拿到当前材料审核员信息
        Long adminId = MyUtil.getCurrentAdminId();
        TbStudent studentShenHe = studentService.getStudentByAdminId(adminId);
        if (Objects.isNull(studentShenHe) || Objects.isNull(studentShenHe.getId()) || Objects.isNull(studentShenHe.getClassId())) {
            log.error("根据adminId查询到的学生数据有误!adminId:{},student:{}", adminId, studentShenHe);
            throw new ApiException("网络错误!请联系管理员!");
        }

        if (Objects.isNull(stuId)) {

            Long classId = studentShenHe.getClassId();
            List<Long> tmpStuIds = studentService.getStudentIdByClassId(classId);

            stuIds.addAll(tmpStuIds);
        } else {
            Long classId = studentShenHe.getClassId();
            //判断该学生是不是当前材料审核员所在班级
            boolean exits = studentService.checkStudentByClassId(classId, stuId);
            if (!exits) return CommonResult.failed("该学生不是该材料审核员班上的学生!");
            stuIds.add(stuId);
        }
        conditionDTO.setStuIds(stuIds);


//        //判断状态
//        Boolean status = condition.getStatus();
//        //为空，则表示查询全部,不做操作
//
//        //不为空
//        if(!Objects.isNull(status)){
//            List<Integer> orderList = new ArrayList<>();
//            Integer order = flowPathService.getCurrentFlow();
//            if(status){
//                //为true，则表示查询已经处理过的记录
//                Integer lastOrder = flowPathService.getLastOrder();
//
//                for(int i=order+1;i<=lastOrder+1;i++){
//                    orderList.add(i);
//                }
//
//                //已经拒绝的申请记录
//                orderList.add(0);
//                log.debug("orderList:{}",orderList);
//            }else{
//                orderList.add(order);
//            }
//            conditionDTO.setStatus(orderList);
//        }

        Integer status = condition.getStatus();
        List<Integer> list = new ArrayList<>();
        if (!Objects.isNull(status)) {
            list.add(status);
        }
        conditionDTO.setStatus(list);

        CommonPage<GpaCheckResP> check = checkService.getCheck(currentPage, pageSize, conditionDTO);

        return CommonResult.success(check);
    }

    //操作者操作绩点申请记录
    @PutMapping("/manage")
    @ApiOperation("审核者操作申请记录")
    public CommonResult operate(@Valid @RequestBody CheckOperate operate) {

        //判断该申请记录的状态是否符合当前角色的操作记录
        boolean correct = checkService.judgeCheckStatus(operate.getCheckId());
        if (!correct) return CommonResult.failed("状态异常!");

        boolean success;

        List<CheckOperateDetail> result = operate.getResult();
        if (result.isEmpty()) return CommonResult.success("提交成功!");
        boolean isPass = result.stream().allMatch(item -> item.getCode() == 1);

        if (isPass) {
            //通过
            success = checkService.consent(operate.getCheckId());
        } else {
            List<CheckOperateDetail> refuseDetails = result.stream().filter(item -> item.getCode() == 2).collect(Collectors.toList());
            //拒绝
            success = checkService.turnDown(operate.getCheckId(), refuseDetails);
        }
        if (success) return CommonResult.success("修改成功!");
        return CommonResult.failed("修改失败!");
    }


    //删除绩点申请记录
    @ApiOperation("学生用户删除自己的申请记录")
    @DeleteMapping("/student/{checkId}")
    public CommonResult delCheck(@PathVariable Long checkId) {

        //判断该申请记录是否属于当前用户
        boolean exist = checkService.judgeCheckStu(checkId);
        if (!exist) {
            log.error("该申请记录不属于当前用户");
            return CommonResult.failed("权限错误!");
        }

        //执行删除操作
        boolean success = checkService.delCheck(checkId);
        if (success) return CommonResult.success("删除成功!");

        return CommonResult.failed("删除失败!");
    }

    @ApiOperation("超级管理员获取申请记录")
    @GetMapping("/admin")
    public CommonResult getCheckAdmin(@RequestParam(name = "currentPage", defaultValue = "1") Long currentPage,
                                      @RequestParam(name = "pageSize", defaultValue = "5") Long pageSize,
                                      GpaCheckGetAdmin condition) {

        GpaCheckConditionDTO conditionDTO = new GpaCheckConditionDTO();
        BeanUtil.copyProperties(condition, conditionDTO);
        CommonPage<GpaCheckResP> check = checkService.getCheck(currentPage, pageSize, conditionDTO);

        return CommonResult.success(check);
    }

    @ApiOperation("超级管理员删除申请记录")
    @DeleteMapping("/admin/{checkId}")
    public CommonResult delCheckAdmin(@PathVariable Long checkId) {
        //执行删除操作
        boolean success = checkService.delCheck(checkId);
        if (success) return CommonResult.success("删除成功!");

        return CommonResult.failed("删除失败!");
    }

}